package notice.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import mq.domain.MqMessageAbnormal;
import mq.util.MqUtil;
import notice.config.MQDeductionConfig;
import notice.dto.DeductionNoticeDto;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @description: 向MQ中发送扣款后通知消息
 * @author: zk
 * @since: 2022-08-16 16:38
 */
@Slf4j
@Component
public class MqDeductionNoticeUtil {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private MqUtil mqUtil;

    /**
     * 向MQ中发送扣款后通知消息
     *
     * @param noticeDto
     */
    public void send(DeductionNoticeDto noticeDto) {
        // 空校验
        Assert.notNull(noticeDto, "noticeDto不能为空！");
        Assert.notNull(noticeDto.getOrderNo(), "DeductionNoticeDto.OrderNo不能为空！");
        Assert.notNull(noticeDto.getEtcTypeId(), "DeductionNoticeDto.EtcTypeId不能为空！");
        Assert.notNull(noticeDto.getOrderType(), "DeductionNoticeDto.OrderType不能为空！");
        Assert.notNull(noticeDto.getCurrPayChannel(), "DeductionNoticeDto.CurrPayChannel不能为空！");

        try {
            Message message = mqUtil.getMessage(noticeDto.getOrderNo(), noticeDto);
            // routingKey = eduction.notice.OrderType
            String routingKey = MQDeductionConfig.ROUTING_KEY_DEDUCTION_NOTICE + MQDeductionConfig.SEPARATE
                    + noticeDto.getOrderType();
            // correlationData-消费者发送到交换机异常时使用
            CorrelationData correlationData = new CorrelationData();
            MqMessageAbnormal mqMessageAbnormal = new MqMessageAbnormal();
            mqMessageAbnormal.setExchange(MQDeductionConfig.EXCHANGE_DEDUCTION_NOTICE);
            mqMessageAbnormal.setRoutingKey(routingKey);
            mqMessageAbnormal.setMessage(JSON.toJSONString(message));
            Message correlationMessage = mqUtil.getMessage(noticeDto.getOrderNo(), mqMessageAbnormal);
            correlationData.setReturnedMessage(correlationMessage);
            // 发送消息
            rabbitTemplate.convertAndSend(MQDeductionConfig.EXCHANGE_DEDUCTION_NOTICE, routingKey, message, correlationData);
        } catch (Exception e) {
            log.error("MQ消息发送失败！", e);
        }
    }
}
